package com.aiti.lulian.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SmsCompont {

    @Resource
    private com.aliyun.dysmsapi20170525.Client smsClient;
    private Gson gson = new Gson();

    @Value("${aliyun.sms.sign}")
    private String signName;

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.endpoint}")
    private String endpoint;

    private Client client;

    @PostConstruct
    public void init() throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret)
                .setEndpoint(endpoint);
        client = new Client(config);
    }



    /**
     * <p>
     * 发送短信验证码
     * </p>
     *
     * @param to         接收验证码的手机号
     * @param templateId 验证码模版ID
     * @param value      验证码
     */
    public boolean send(String to, String templateId, String value) {

        Map<String, String> codeMap = new HashMap<>(16);
        codeMap.put("code", value);
        String codeStr = gson.toJson(codeMap);

        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(to)
                .setTemplateCode(templateId)
                .setSignName(signName)
                .setTemplateParam(codeStr);
        try {
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if (StringUtils.equals(sendSmsResponse.body.code, "OK")) {
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("短信发送失败:{}", e);
            return false;
        }
    }
}
